<?php
namespace app\admin\classes;

use app\admin\classes\ExportData;
use core\Api;
use core\V;
use core\Res;
use core\Func;


/**
 * 基础管理类
 */
class BasicSearch extends \C {

  static $model;
  // 本页地址
  static $hash="";
  // 展开的菜单
  static $menuHash="";

  // 是否可下载
  static $download=true;

  // 变量列表
  static $var="id,remark";

  static $title=[
    "show"=>true,
    "title"=>"",
    "breadcrumb"=>[],
    "subtitle"=>"",
    "panel"=>"",
  ];
  // 配置选项
  static $conf=[
    // 文本模板配置
    "tpl"=>"",
    // 视图文件配置
    "view"=>""
  ];


  public function search_body(){
    return "";
  }

  public function result_body(){
    return "";
  }


  protected function btn($conf,$width="100px"){
    $btn="";
    if (!empty($conf)){
      $btn='
      <el-table-column
        fixed="right"
        label="操作"
        align="right"
        header-align="right"
        width="'.$width.'">
        <template slot-scope="scope">
      ';
      foreach ($conf as $v) {
        if (empty($v["name"])) continue;
        $name=$v["name"];
        $class=(empty($v["class"]))?"":$v["class"];
        $onclick=(empty($v["onclick"]))?"":'@click="'.$v["onclick"].'(scope.row)"';
        $b='<el-button class="result-btn '.$class.'" '.$onclick.' type="text" size="small">'.$name.'</el-button>';
        $btn.=$b;
      }

      $btn.='
        </template>
      </el-table-column>
      ';
    }

    $this->VD([
      "___btn___"=>$btn,
    ]);
  }


  // 钩子函数
  // 所有查询拼接之前
  protected function before_search($form){
    return $form;
  }
  // 所以查询拼接之后
  protected function after_search(&$query){

  }
  // 获取结果之前
  protected function before_result(&$query){
    $query->hidden(["create_at","update_at","delete_at"]);
  }
  // 获取结果之后
  protected function after_result(&$res,$list){
    return $list;
  }

  // 分页处理
  protected function set_page(&$query){
    $page=input("page","1");
    $pagesize=input("pagesize","10");
    $query->page($page,$pagesize);
  }
  // 分页处理
  protected function set_order(&$query){
    $order=input("order");
    if ((!empty($order)) && is_array($order)){
      $query->order($order);
    }else{
      $query->order(["id"=>"desc"]);
    }
  }


  // 处理每一个参数
  protected function search_filter(&$query,$key,$value){

  }



  // 预处理函数
  protected function like(&$query,$key,$value){
    if (!empty($value)){
      $query->where($key,"like","%$value%");
    }
  }


  // 首页
  public function index(){
    $conf=static::$conf;
    $conf["title"]=static::$title;
    $this->wapper([
      "show"=>$conf["title"]["show"],
      "title"=>$conf["title"]["title"],
      "breadcrumb"=>$conf["title"]["breadcrumb"],
      "panel"=>isset($conf["title"]["panel"]),
      "subtitle"=>$conf["title"]["subtitle"],

    ]);

    $this->VD([
      "apiBase"=>static::$hash,
      "footer_btn_download"=>empty(static::$download)?"0":"1",
    ]);

    if (!empty($conf["view"])){
      return view($conf["view"],$this->VD());
    }else{
      if (empty($conf["tpl"])) $conf["tpl"]=BasicSearchTemplet::index();
      return $this->displayout("index",$conf["tpl"],$this->VD());
    }


  }
  protected function get_query(){

    $query= false ;

    // 处理筛选条件
    $form=input("form",[]);
    $form=$this->before_search($form);

    if (!empty($form)){
      if (is_array($form)){
        $query=static::$model::withSearch(array_keys($form),$form);
        foreach ($form as $key => $value) {
          $this->search_filter($query,$key,$value);

        }
      }
    }
    if ($query === false) $query=static::$model::where(1);

    $this->after_search($query);
    return $query;
  }
  protected function make_list(&$query){
    $res=$query->all();
    $list=$res->toArray();
    return $list;
  }
  protected function get_list(&$query){
    $this->before_result($query);
    $list=$this->make_list($query);
    $list=$this->after_result($res,$list);
    return $list;
  }

  public function getresult(){


    if(method_exists($this,'raw_query')){
      $res=$this->raw_query();
      $total=$res["total"];
      $list=$res["list"];
    }else{
      $query=$this->get_query();

      $total=$query->count();

      $this->set_page($query);
      $this->set_order($query);

      $list=$this->get_list($query);
    }


    Api::ok([
      "total"=>$total,
      "list"=>$list,
    ]);

  }

  public function getdownload(){
    if(method_exists($this,'raw_query')){
      $res=$this->raw_query();
      $total=$res["total"];
      $list=$res["list"];
    }else{
      $query=$this->get_query();
      $this->set_order($query);
      $list=$this->get_list($query);
    }



    $type=input("type");
    V::empty($type,"csv");

    $exp=new ExportData($list);
    $exp->outfile($type);


  }

  // 重写display方法
  protected function displayout($key,$t="",$v=[],$c=[]){

    if ($key=="index"){

      $t=str_replace("___result___",$this->result_body(),$t);
      $t=str_replace("___search___",$this->search_body(),$t);

    }

    $t=str_replace("___vue___",$this->getVD("___vue___"),$t);
    $t=str_replace("___css___",$this->getVD("___css___"),$t);
    $t=str_replace("___btn___",$this->getVD("___btn___"),$t);
    $t=str_replace("___footerbtn___",$this->getVD("___footerbtn___"),$t);

    if (!empty(static::$menuHash)){
      $this->menuActive(static::$menuHash);
    }

    return $this->display($t,$v,$c);
  }

}

/**
 * 模板
 */
class BasicSearchTemplet
{
  static function index(){


    $html=<<<'CODE'
    {layout name="/public/layout_index" /}

    <style>
    .is-right > .cell{
      display:inline;
    }
    .el-collapse-item__wrap {
        border-bottom: 0px;
        padding-top:30px;
    }
    .el-collapse-item__header {
        border-bottom: 0px solid #ebeef5;
        height: 28px;
        line-height: 28px;
    }
    .el-collapse-item__header.is-active {
        border-bottom: 1px solid #ebeef5;
        height: 48px;
        line-height: 48px;
    }
    .el-collapse-item__arrow {
      height: 30px;
      line-height: 30px;
    }
    .hover:hover{
      color:#1e88e5 !important;
    }


    ___css___
    </style>

    <div id="app" v-cloak>

      <div class="card">
        <div class="card-body">
          <el-collapse v-model="activeNames" style="border-top:0px;border-bottom:0px;">
            <el-collapse-item name="1" >
              <template slot="title">
                <h3 class="card-title hover">查询条件</h3>

              </template>
                <el-form
                  class="row"
                  :model="form"
                  label-width="90px"
                  size="mini"
                  @submit.prevent="return false">
                  ___search___
                  <el-form-item class="col-12">
                    <el-button class="btn-info waves-effect waves-light" size="medium" type="primary" @click="Search">查询</el-button>
                  </el-form-item>
                </el-form>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>


      <c-card title="查询结果" v-show="result_show" v-loading="result_loading" footer="true">
        <template slot="header-right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page.currentPage"
              :page-sizes="[10, 20, 50, 100, 300, 500]"
              :page-size="page.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total">
            </el-pagination>
        </template>
        <template slot="footer-right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page.currentPage"
              :page-sizes="[10, 20, 50, 100, 300, 500]"
              :page-size="page.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total">
            </el-pagination>
        </template>

        <template slot="footer">
            <el-button
              @click="Search"
              data-toggle="tooltip"
              title="刷新"
              class="btn-warning waves-effect waves-light"
              type="info"
              icon="el-icon-refresh"
              style="outline: none;"
              circle>
            </el-button>
            <el-button
              @click="goTop"
              data-toggle="tooltip"
              title="筛选"
              class="btn-success waves-effect waves-light"
              type="warning"
              icon="el-icon-search"
              style="outline: none;"
              circle>
            </el-button>
            <el-button
              v-if="footer_btn.download"
              @click="download"
              data-toggle="tooltip"
              title="下载"
              class="result-download btn-info waves-effect waves-light"
              type="danger"
              icon="el-icon-download"
              style="outline: none;"
              circle>
            </el-button>
            ___footerbtn___

        </template>




            <el-table

              :data="list"
              style="width: 100%"
            >
              ___result___
              ___btn___
            </el-table>


      </c-card>


    </div>



    <script>
    var mixin = {
      ___vue___
    };
    var base_mixin={
      data:{
        apiBase:"{$apiBase}",
        footer_btn:{
          download:{$footer_btn_download}
        },
        activeNames:["1"],
        result_show:false,
        result_loading:true,
        form:{},
        order:{},
        page: {
          currentPage:1,
          total: 0,
          pagesize: 10
        },
        list:[]

      },
      methods: {
        init(){
          //this.Search();
        },
        Search: function(){
          this.activeNames=[];
          this.result_show=true;
          this.result_loading=true;

          var that=this;
          var postData={
            order:this.order,
            form: this.form,
            page: this.page.currentPage,
            pagesize: this.page.pagesize
          };
          APP.ajax(this.apiBase+"/getresult",postData,function(msg){
            that.result_loading=false;
            if (msg.result){
              that.page.total=parseInt(msg.data.total);
              that.list=msg.data.list;
            }else{
              APP.alert(msg.data);
            }
          });
        },
        handleSizeChange: function(val) {
          this.page.pagesize=val;
          this.Search();
        },
        handleCurrentChange: function(val) {
          this.page.currentPage=val;
          this.Search();
        },
        goTop:function(){
          this.activeNames=["1"];
          $("html,body").animate({scrollTop:0},1000);
        },
        download:function(type){
          var postData={
            order:this.order,
            form: this.form,
            type:type
          };
          var temp = document.createElement("form");
          temp.action = this.apiBase+"/getdownload";
          temp.method = "post";
          temp.target = "_blank";
          temp.style.display = "none";
          var opt = document.createElement("textarea");
          opt.name = "data";
          opt.value = JSON.stringify(postData);
          temp.appendChild(opt);
          document.body.appendChild(temp);
          temp.submit();
        }

      },
      mounted(){
        var that=this;
        this.$nextTick(function () {
          that.init();
        })
      }
    };
    var main=new Vue({
      el:"#app",
      mixins: [base_mixin,mixin],

    });

    </script>


CODE;
    return $html;

  }

}
